import api from '@/api'
import { deepCopy, setPage } from '@/utils/util'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null,
        title: null
    }
}

const state = {

    data: {
        roles: [],
        rights: []
    },

    ui: {
        page: deepCopy(initPage)
    }
}

const getters = {
    roles: state => state.data.roles,
    rights: state => state.data.rights,

    rolesTotal: state => state.ui.page.total
}

// actions
const actions = {

    getRoles({ state, commit }, params) {
        api.getRoles({
            loading: true,
            method: 'post',
            data: params ? params : state.ui.page,
            success: (res) => {
                const { pages, total } = res
                commit('SETROLEPAGE', { pages, total })
                
                const roles = res.content
                commit('SETROLES', {
                    roles: roles
                })
            }
        })
    },

    addRole({ dispatch }, params) {
        api.addRole({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getRoles')
            }
        })
    },

    removeRole({ dispatch }, params) {
        api.removeRole({
            method: 'post',
            data: params,
            success: (res) => {
                dispatch('getRoles')
            }
        })
    },

    editRole({ dispatch }, params) {
        api.editRole({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getRoles')
            }
        })
    },

    getAuthorities({ commit }, params) {
        api.getAuthorities({
            method: 'get',
            data: params,
            success: (res) => {
                console.log(res)
                let rights = res
                commit('SETRIGHTS', {
                    rights
                })
            }
        })
    },

}

// mutations
const mutations = {

    SETROLES(state, payload) {
        state.data.roles = payload.roles
    },

    SETROLEPAGE(state, page) {
        page && setPage(state.ui.page, page)
    },

    SETRIGHTS(state, payload) {
        state.data.rights = payload.rights
    }

}

export default {
    state,
    getters,
    actions,
    mutations
}